<?php
/*
 * 用户组
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\facade\Db;
use think\facade\Session;
use app\common\model\AuthGroup;

class Group extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function lists()
    {
        $list = AuthGroup::getAuthGroup();
        return $this->fetch('index',['list'=>$list]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $result = AuthGroup::create($this->request->param());
            !$result && $this->error($this->errorMsg);
            insert_admin_log('添加了用户组');
            $this->success('添加成功');
        }
        $authRule = Db::table('auth_rule')->field('id,name title,pid')->where(['status' => 1])->order('sort_order asc')->select()->toArray();
        return $this->fetch('save', ['authRule' => list_to_tree($authRule)]);
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $verify = input('_verify', true);
            //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'authGroup');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            //更新数据
            $result = AuthGroup::update($param);
            !$result && $this->error($this->errorMsg);
            // insert_admin_log('修改了用户组');
            $this->success('修改成功');
        }
        $data = Db::table('auth_group')->find(input('id'));
        $rules_arr = explode(',',$data['rules']);
        $authRule = Db::table('auth_rule')->field('id,name title,pid')->where(['status' => 1])->select()->toArray();
        foreach ($authRule as $k => $v) {
            if(in_array($v['id'],$rules_arr) && in_array($v['pid'],$rules_arr)){
                $counts = Db::table('auth_rule')->where(['pid'=>$v['id'],'status' => 1])->count('id');
                if(!$counts) $authRule[$k]['checked'] = true;
            }
        }
        return $this->fetch('save', ['data' => $data, 'authRule' => list_to_tree($authRule)]);
    }

    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Db::table('auth_group_access')->where('group_id',$param['id'])->find() && $this->error('当前组正在被使用,无法删除');
            AuthGroup::destroy($param['id']);
            insert_admin_log('删除了用户组');
            $this->success('删除成功');
        }
    }


}
